package br.com.dips.dao;

import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import br.com.dips.enums.Situacao;
import br.com.dips.model.Organizacao;

public class OrganizacaoDAO extends BaseDAO {
	
	public Organizacao consultar(Integer id) {
		Query query = this.getEm().createNamedQuery("Organizacao.findById", Organizacao.class);
		query.setParameter("id", id);
		
		return (Organizacao) query.getSingleResult();
	}

	public Organizacao incluir(Organizacao org) {
		this.getEm().persist(org);
		
		return org;
	}
	
	public void alterar(Organizacao org) {
		this.getEm().merge(org);
	}
	
	@SuppressWarnings("unchecked")
	public List<Organizacao> listar(int start, int pageSize, String sortField, String sortOrder, Map<String, String> filters) {
		StringBuffer jpqlQuery = new StringBuffer("select org from Organizacao org ");

	    if (filters != null & !filters.isEmpty()) {
	      jpqlQuery.append(" where 1 = 1 ");
	      for (String key : filters.keySet()) {
	        jpqlQuery.append(" and UPPER(org." + key + ") like '%" + filters.get(key).toUpperCase() + "%' ");
	      }
	    }

	    if (sortField != null && !"".equals(sortField)) {
	      jpqlQuery.append(" order by UPPER(org." + sortField + ") ");

	      if (sortOrder != null && !"".equals(sortOrder) && !"UNSORTED".equals(sortOrder)) {
	        jpqlQuery.append("ASCENDING".equals(sortOrder) ? "asc" : "desc");
	      }

	      jpqlQuery.append(", org.id ");

	      if (sortOrder != null && !"".equals(sortOrder) && !"UNSORTED".equals(sortOrder)) {
	        jpqlQuery.append("ASCENDING".equals(sortOrder) ? "asc" : "desc");
	      }
	    }

	    Query query = this.getEm().createQuery(jpqlQuery.toString());
	    query.setFirstResult(start);
	    query.setMaxResults(pageSize);
	    return query.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	public List<Organizacao> listarPorSituacao(Situacao situacao) {
		Query query = this.getEm().createNamedQuery("Organizacao.findBySituacao");
		query.setParameter("situacao", situacao.getCodigo());
		
		return query.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	public List<Organizacao> listar() {
		Query query = this.getEm().createNamedQuery("Organizacao.findAll");
		
		return query.getResultList();
	}
	
	public int conta(Map<String, String> filters) {
		StringBuffer jpqlQuery = new StringBuffer("select COUNT(org) from Organizacao org ");

		if (filters != null & !filters.isEmpty()) {
			jpqlQuery.append(" where 1 = 1 ");
			for (String key : filters.keySet()) {
				jpqlQuery.append(" and UPPER(org." + key + ") like '%" + filters.get(key).toUpperCase() + "%'");
			}
		}

		Query query = this.getEm().createQuery(jpqlQuery.toString());
		return ((Long) query.getSingleResult()).intValue();
	}

}
